package edu.yuhf.pac;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class StorageForReentrantLock implements Storage{

	private Lock lock = new ReentrantLock();
	
	Condition full=lock.newCondition();
	Condition empty=lock.newCondition();
	
	public void produce(int number) {
			lock.lock();
			try {
				while(list.size()+number>=MAX_NUM) {
					System.out.println("仓库已满，无法生产！"+number+"件产品！");
					try {
						full.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				for(int i=0;i<number;i++) {
					list.add(new Product(i,Thread.currentThread().getName()+"_"+i));
				}
				System.out.println("已经生产了"+number+"件产品,仓库中共有"+list.size()+"件产品");
				empty.signal();
			}finally {
				lock.unlock();
			}
			
	}
	public void buy(int number) {
		lock.lock();
		try {
			while(list.size()-number<=0) {
				System.out.println("仓库存货不足，无法消费"+number+"件产品！");
				try {
					empty.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(int i=0;i<number;i++) {
				list.remove();
			}
			System.out.println("已经销费了"+number+"件产品，仓库中还有"+list.size()+"件产品");
			full.signal();
		}finally {
			lock.unlock();
		}
	}

}
